package com.example.htmlfx.component;

import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.Background;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 * 加载动画组件
 *
 * @author gzkemays
 * @date 2021/8/5
 */
public class LoadingProgressComponent {
  private final Stage stage;
  private final ProgressIndicator progressIndicator;

  @FunctionalInterface
  public interface FailOpera {
    void operation();
  }

  public LoadingProgressComponent(Stage primaryStage, String loadingText) {
    stage = new Stage();
    progressIndicator = new ProgressIndicator();
    // 窗口父子关系
    stage.initOwner(primaryStage);
    stage.initStyle(StageStyle.UNDECORATED);
    stage.initStyle(StageStyle.TRANSPARENT);
    stage.initModality(Modality.APPLICATION_MODAL);

    // progress bar
    Label label = new Label(loadingText);
    label.setTextFill(Color.BLUE);
    // label.getStyleClass().add("progress-bar-root");
    progressIndicator.setProgress(-1F);
    // progressIndicator.getStyleClass().add("progress-bar-root");
    VBox vBox = new VBox();
    vBox.setSpacing(10);
    vBox.setBackground(Background.EMPTY);
    vBox.getChildren().addAll(progressIndicator, label);

    Scene scene = new Scene(vBox);
    scene.setFill(null);
    stage.setScene(scene);
  }

  public void activateProgressBar(final Task<?> task, FailOpera fail) {
    progressIndicator.progressProperty().bind(task.progressProperty());
    Thread inner = new Thread(task);
    inner.start();
    // javafx 的 task 监听成功后执行
    task.setOnSucceeded(event -> stage.close());
    task.setOnFailed(
        event -> {
          fail.operation();
          stage.close();
        });
    stage.show();
  }

  public Stage getDialogStage() {
    return stage;
  }

  public void cancelProgressBar() {
    stage.close();
  }
}
